package com.biubiux2.handler;

import com.biubiux2.message.MessageType;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author Lijinbao
 * @since 8/9/2022 11:23 AM
 */
@Slf4j(topic = "HEARTBEAT")
public class HeartBeatServerHandler extends ChannelInboundHandlerAdapter {

    public static ByteBuf PONG;

    public static ByteBuf PING;

    static {
        byte[] pingBytes = "PING".getBytes(StandardCharsets.UTF_8);
        PING = PooledByteBufAllocator.DEFAULT.directBuffer(4 + pingBytes.length);
        PING.writeInt(MessageType.HEARTBEAT_PING);
        PING.writeBytes(pingBytes);

        byte[] pongBytes = "PONG".getBytes(StandardCharsets.UTF_8);
        PONG = PooledByteBufAllocator.DEFAULT.directBuffer(4 + pongBytes.length);
        PONG.writeInt(MessageType.HEARTBEAT_PONG);
        PONG.writeBytes(pongBytes);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
//                log.debug("很久没收到客户端的消息了，决定关闭连接。");
//                ctx.close();
            } else if (e.state() == IdleState.WRITER_IDLE) {
                log.debug("该发送PING表示我还在了。");
                ctx.writeAndFlush(PING.retainedDuplicate());
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        int type = ((ByteBuf) msg).readInt();
        if (type == MessageType.HEARTBEAT_PING) {
            // "PING"
            ctx.writeAndFlush(PONG.retainedDuplicate());
            log.debug("收到PING，返回PONG");
            byteBuf.release();
        } else if (type == MessageType.HEARTBEAT_PONG) {
            // "PONG"消息类型
            log.debug("收到PONG。");
            byteBuf.release();
        } else {
            byteBuf.resetReaderIndex();
            super.channelRead(ctx, byteBuf);
        }
    }
}
